package client

import (
	"ws-demo-go/internal/message/common"
	"ws-demo-go/internal/transport/client"
	"ws-demo-go/pkg/logger"
)

type Client struct {
	transClient *client.Client        // 传输层客户端
	onMessage   func(*common.Message) // 消息接收回调（交给上层处理）
}

// NewClient 创建消息层客户端实例
func NewClient(serverAddr string, reconnect bool) *Client {
	mc := &Client{
		transClient: client.NewClient(serverAddr, reconnect),
	}
	mc.transClient.SetOnMessage(mc.onTransportMessage)
	return mc
}

// Connect 连接到服务端
func (mc *Client) Connect() error {
	return mc.transClient.Connect()
}

// SendMessage 发送 Message 消息
func (mc *Client) SendMessage(msg *common.Message) error {
	// 编码 Message 为二进制数据
	data, err := common.Encode(msg)
	if err != nil {
		logger.Error("Encode message failed: %v", err)
		return err
	}

	// 通过传输层发送二进制数据
	return mc.transClient.SendBytes(data)
}

// SetOnMessage 设置消息接收回调函数
func (mc *Client) SetOnMessage(callback func(*common.Message)) {
	mc.onMessage = callback
}

// Close 关闭客户端连接
func (mc *Client) Close() {
	mc.transClient.Close()
}

// IsConnected 检查是否已连接
func (mc *Client) IsConnected() bool {
	return !mc.IsClosed()
}

// IsClosed 检查是否已关闭
func (mc *Client) IsClosed() bool {
	return mc.transClient.IsClosed()
}

// 传输层消息处理函数，将二进制数据解码为 Message 对象
func (mc *Client) onTransportMessage(data []byte) {
	// 解码二进制数据为Message对象
	msg := &common.Message{}
	err := common.Decode(data, msg)
	if err != nil {
		logger.Error("Decode message failed: %v", err)
		return
	}

	// 调用业务层回调处理 Message
	if onMessage := mc.onMessage; onMessage != nil {
		onMessage(msg)
	}
}
